package com.bjpowernode.javase.collection.review;

import java.util.HashMap;
import java.util.function.BiFunction;
import java.util.function.Function;

public class MapComputeTest {
    public static void main(String[] args) {
        String str = "hello java, i am vary happy! nice to meet you";
        HashMap<Character, Integer> hashMap = noCount(str);
        hashMap.forEach((k,v)-> System.out.println(k + "=" + v));
        System.out.println("=======================");
        HashMap<Character, Integer> hashMap1 = withCount(str);
        hashMap1.forEach((k,v)-> System.out.println(k + "=" + v));
        System.out.println("========================");
        Function<Integer,Integer> fun1 = arg -> arg * arg;
        System.out.println(fun1.apply(10));
        BiFunction<Integer,Integer,Integer> fun2 = (arg1,arg2) -> arg1 + arg2;
        System.out.println(fun2.apply(10,20));


    }

    public static HashMap<Character,Integer> noCount(String str){
        HashMap<Character,Integer> hashMap = new HashMap<>();
        char[] chars = str.toCharArray();
        for (char aChar : chars) {
            Integer num;
            if((num = hashMap.get(aChar)) == null){
                hashMap.put(aChar,1);
            }else {
                hashMap.put(aChar,++num);
            }
        }
        return  hashMap;
    }

    public static HashMap<Character,Integer> withCount(String str){
        HashMap<Character,Integer> hashMap = new HashMap<>();
        char[] chars = str.toCharArray();

        for (char aChar : chars) {
            hashMap.compute(aChar,(k,v)->null==v ? 1 : ++v);
        }
        return hashMap;
    }

}
